﻿//bibaoke.com

using System.Collections.Generic;
using System.Windows.Forms;
using System.Linq;

namespace Less.WebBrowserQuery
{
    internal abstract class ElementFilter
    {
        internal ElementFilter Next
        {
            get;
            set;
        }

        internal ElementFilter Child
        {
            get;
            set;
        }

        internal IEnumerable<HtmlElement> Eval(HtmlDocument document)
        {
            IEnumerable<HtmlElement> elements = this.EvalThis(document);

            return this.EvalOthers(document, elements);
        }

        internal IEnumerable<HtmlElement> Eval(HtmlDocument document, IEnumerable<HtmlElement> source)
        {
            IEnumerable<HtmlElement> elements = this.EvalThis(document, source);

            return this.EvalOthers(document, elements);
        }

        protected abstract IEnumerable<HtmlElement> EvalThis(HtmlDocument document);

        protected abstract IEnumerable<HtmlElement> EvalThis(HtmlDocument document, IEnumerable<HtmlElement> source);

        private IEnumerable<HtmlElement> EvalOthers(HtmlDocument document, IEnumerable<HtmlElement> elements)
        {
            if (this.Next.IsNotNull())
            {
                elements = this.Next.Eval(document, elements);
            }
            else
            {
                if (this.Child.IsNotNull())
                {
                    elements = this.Child.Eval(document, elements.SelectMany(i => i.Children.Cast<HtmlElement>()));
                }
            }

            return elements;
        }
    }
}
